<template>
  <div class="template-list-container">
    <!-- 顶部导航栏 -->
    <div class="list-header">
      <el-button @click="handleBack" class="back-btn">
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
      <h2>模板管理</h2>
      <div class="actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索模板名称..."
          prefix-icon="el-icon-search"
          class="search-input"
        ></el-input>
        <el-button
          icon="el-icon-plus"
          @click="handleCreateNew"
          class="create-btn"
        >
          新建模板
        </el-button>
      </div>

      <!-- <el-button @click="refreshTemplates" type="primary" size="small">
        <i class="el-icon-refresh"></i> 刷新
      </el-button> -->
    </div>

    <!-- 模板分类标签 -->
    <div class="category-tabs">
      <el-tag
        v-for="category in categories"
        :key="category.value"
        :class="{ active: activeCategory === category.value }"
        @click="activeCategory = category.value"
        class="category-tag"
      >
        {{ category.label }}
      </el-tag>
    </div>

    <!-- 模板列表 -->
    <div class="templates-grid">
      <div
        v-for="template in filteredTemplates"
        :key="template.id"
        class="template-card"
      >
        <!-- 模板图标 -->
        <div class="template-icon">
          <font-awesome-icon
            :icon="getFileIcon(template.fileType)"
            :style="{ color: getTemplateColor(template.fileType) }"
          />
        </div>

        <!-- 模板信息 -->
        <div class="template-info">
          <h3 class="template-name" :title="template.name">
            {{ template.name }}
          </h3>
          <p class="template-meta">
            <span class="type-label">{{
              getFileTypeLabel(template.fileType)
            }}</span>
            <span class="update-time"
              >更新于 {{ parseTime(template.updateTime) }}</span
            >
          </p>
        </div>

        <!-- 操作按钮（悬停显示） -->
        <div class="template-actions">
          <el-button
            icon="el-icon-edit"
            size="mini"
            @click.stop="handleEdit(template)"
            class="action-btn edit-btn"
          ></el-button>
          <!-- <el-button
            icon="el-icon-download"
            size="mini"
            @click.stop="handleDownload(template)"
            class="action-btn download-btn"
          ></el-button> -->
          <el-button
            icon="el-icon-delete"
            size="mini"
            @click.stop="handleDelete(template)"
            class="action-btn delete-btn"
          ></el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredTemplates.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="el-icon-folder-opened"></i>
      </div>
      <p class="empty-text">暂无符合条件的模板</p>
      <el-button type="primary" @click="handleCreateNew">
        <i class="el-icon-plus"></i> 立即创建
      </el-button>
    </div>
  </div>
</template>

<script>
import { listTemplate, deleteTemplate } from "@/api/zhishiku/template";

export default {
  name: "TemplateListView",
  data() {
    return {
      templates: [],
      searchKeyword: "",
      activeCategory: "all",
      categories: [
        { label: "全部模板", value: "all" },
        { label: "文本文档", value: "text" },
        { label: "电子表格", value: "spreadsheet" },
        { label: "演示文稿", value: "presentation" },
      ],
      total: 0,
      pageNum: 1,
      pageSize: 10000,
    };
  },
  computed: {
    filteredTemplates() {
      return this.templates
        .filter((template) => {
          const categoryMatch =
            this.activeCategory === "all"
              ? true
              : template.category === this.activeCategory;
          const keywordMatch =
            this.searchKeyword === ""
              ? true
              : template.name
                  .toLowerCase()
                  .includes(this.searchKeyword.toLowerCase());
          return categoryMatch && keywordMatch;
        })
        .map((template) => ({
          ...template,
        }));
    },
  },
  mounted() {
    this.fetchTemplates();
  },
  methods: {
    // refreshTemplates() {
    //   this.$emit("refreshTemplates");
    // },

    async fetchTemplates() {
      try {
        const response = await listTemplate({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        });
        if (response.code === 200) {
          this.templates = response.rows || [];
          this.total = response.total || 0;
        } else {
          this.$message.error("加载模板失败：" + response.msg);
        }
      } catch (error) {
        console.error("模板列表请求失败", error);
        this.$message.error("加载模板时发生错误");
      }
    },

    handleBack() {
      this.$emit("back");
    },

    handleCreateNew() {
      // 向父组件发送事件，通知需要切换到模板类型选择视图
      this.$emit("createNewTemplate");
    },

    handleEdit(template) {
      this.$emit("editTemplate", template);
    },

    // handleDownload(template) {
    //   window.open(`/api/template/download?id=${template.id}`, "_blank");
    // },

    handleDelete(template) {
      this.$confirm(`确定要删除模板"${template.name}"吗？`, "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await deleteTemplate(template.id);
            if (response.code === 200) {
              this.$message.success("删除成功");
              this.fetchTemplates();
            } else {
              this.$message.error("删除失败：" + response.msg);
            }
          } catch (error) {
            console.error("删除模板失败", error);
            this.$message.error("删除时发生错误");
          }
        })
        .catch(() => {
          // 取消删除
        });
    },

    getFileIcon(fileType) {
      switch (fileType) {
        case "docx":
          return ["fas", "file-word"]; // faFileWord 对应的图标标识，'fas' 代表 solid 风格
        case "xlsx":
          return ["fas", "file-excel"]; // faFileExcel 对应的图标标识
        case "pptx":
          return ["fas", "file-powerpoint"]; // 如果有 PPT 图标，类似这样，也可从 Font Awesome 找对应
        default:
          return ["fas", "file"]; // 默认文件图标
      }
    },

    getTemplateColor(fileType) {
      switch (fileType) {
        case "docx":
          return "#2c82e0";
        case "xlsx":
          return "#36b37e";
        case "pptx":
          return "#ff5630";
        default:
          return "#8993a4";
      }
    },

    getFileTypeLabel(fileType) {
      switch (fileType) {
        case "docx":
          return "Word文档";
        case "xlsx":
          return "Excel表格";
        case "pptx":
          return "PPT演示";
        default:
          return "其他文件";
      }
    },
  },
};
</script>

<style scoped>
.el-icon-arrow-left {
  font-size: 15px;
}
.template-list-container {
  padding: 24px;
  background-color: #f5f7fa;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

/* 头部导航 */
.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.back-btn {
  background: linear-gradient(135deg, #1e5799 0%, #207cca 100%);
  background-color: transparent;
  color: white;
  font-size: 15px;
  border: none;
  padding: 8px 12px;
  height: 32px;
  border-radius: 9px;
}
.back-btn:hover {
  background-color: #f5f5f5;
  color: #409eff;
}

.list-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 280px;
  --el-input-height: 36px;
}

.create-btn {
  --el-button-size: 36px;
  padding: 0 16px;
  background: linear-gradient(135deg, #1e5799 0%, #207cca 100%);
  color: white;
  height: 32px;
  font-weight: 400;
  border-radius: 9px;
}

/* 分类标签 */
.category-tabs {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.category-tag {
  padding: 1px 17px;
  font-size: 14px;
  height: 29px;
  cursor: pointer;
  border-radius: 9px;
  background: linear-gradient(135deg, #37669c 0%, #588fd1 100%);
  border: none;
  color: white;
  transition: all 0.2s;
}
.category-tag.active {
  background: linear-gradient(135deg, #1a4b80 0%, #4a7eb3 100%);
  color: white;
  border: none;
}
.category-tag:hover {
  background-color: #f0f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

/* 模板网格布局 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 28px;
  margin-bottom: 40px;
}

/* 模板卡片 */
.template-card {
  overflow: visible;
  background-color: #ffffff;
  border: 1px dotted #2e8be2 ;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 140px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
}
.template-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.template-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  font-size: 24px;
}

.template-info {
  flex: 1;
}

.template-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.template-meta {
  margin: 0;
  font-size: 13px;
  color: #909399;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.type-label {
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.update-time {
  font-size: 12px;
}

/* 操作按钮组 - 纯CSS控制 */
.template-actions {
  opacity: 0; /* 初始隐藏 */
  pointer-events: none; /* 初始禁用鼠标事件，避免误触 */
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  transition: opacity 0.3s ease;
  position: relative;
  z-index: 10;
}
/* 鼠标悬停在卡片上时显示按钮 */
.template-card:hover .template-actions {
  opacity: 1;
  pointer-events: auto; /* 启用鼠标事件 */
}

.action-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 6px;
}
.action-btn.edit-btn {
  background-color: #f6ffed;
  color: #52c41a;
  border-color: #b7eb8f;
}
.action-btn.edit-btn:hover {
  background-color: #eaffd0;
}

.action-btn.download-btn {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}
.action-btn.download-btn:hover {
  background-color: #bae7ff;
}

.action-btn.delete-btn {
  background-color: #fff2f0;
  color: #ff4d4f;
  border-color: #ffccc7;
}
.action-btn.delete-btn:hover {
  background-color: #ffe8e6;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  background-color: #ffffff;
  border-radius: 12px;
  margin-top: 20px;
}

.empty-icon {
  font-size: 64px;
  color: #c9cdd4;
  margin-bottom: 24px;
}

.empty-text {
  font-size: 16px;
  color: #8c8c8c;
  margin-bottom: 24px;
}
</style>
